package cn.player.act;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.List;

import cn.player.R;
import cn.player.adapter.ChannelInfoAdapter;
import cn.player.entity.ChannelInfo;
import cn.player.entity.ChannelNav;
import cn.player.view.ListViewCompat;
import cn.player.view.SlideView;
import cn.player.view.SlideView.OnSlideListener;
import cntv.player.engine.Const;
import cn.player.media.entity.VideoInfo;
import cn.player.media.util.ParseUtil;

public class ChannelListActivity extends BaseActivity implements OnSlideListener {
	 
//	private SwipeRefreshLayout //sRefreshLayout;
//	private MyListView lvChannelList; 
//	private ListView lvChannelList; 
	private ListViewCompat lvChannelList; 
	private LinearLayout mLlLoading;
	private String channelNavUrl;
	private List<ChannelNav> channelCates;
	private String cctvListUrl;//央视频道地址
	private String guardListUrl;//卫士频道地址
	private String localListUrl;//地方频道地址
	private List<ChannelInfo> cctvChannelInfos;
	private List<ChannelInfo> guardChannelInfos;
	private List<ChannelInfo> localChannelInfos;
	
	private ChannelInfoAdapter channelInfoAdapter;
	
	private int currentItem;
	
	protected SlideView mLastSlideViewWithStatusOn; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.channel_list_view);
		
		addMenuOnWindow();
		
		channelNavUrl = app.getBaseUrls().get(Const.KEY_CHAN_URL).getUrl();
		currentItem = R.id.channel_cctv;
		
		findViews();
		
		//sRefreshLayout.setColorScheme(R.color.red, R.color.blue, R.color.yellow, R.color.green);
		
		setListener();
		//sRefreshLayout.setRefreshing(true);
		initJsonData(channelNavUrl); 
	}
	
	private void findViews() {
		// TODO Auto-generated method stub
		//sRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh);
		lvChannelList = (ListViewCompat)findViewById(R.id.lv_live_list);
		
		mLlLoading = (LinearLayout)findViewById(R.id.ll_loading);
		lvChannelList.setEmptyView(mLlLoading);
	}

	private void setListener() {
		// TODO Auto-generated method stub
		/*lvChannelList.setOnRersh(new OnRefreshListener() {
			
			@Override
			public void OnRefresh() {
				// TODO Auto-generated method stub
				if(cctvListUrl == null){
					initJsonData(channelNavUrl); 
				}else{
					initJsonData(cctvListUrl);
				}
			}
		});*/
		/*sRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				reLoadData(currentItem,true);
			}
		});*/
		/*lvChannelList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
//				position = (position - 1 < 0) ? 0 : position - 1;//减去下拉刷新头部位置
				onChannelItemClick(position);  
			}
		});*/
	}
	
	@Override
	protected void initDataSuccess(String url, JSONObject response) {
		// TODO Auto-generated method stub
		super.initDataSuccess(url, response);
		try {
			if(url.equals(channelNavUrl)){
				channelCates = ChannelNav.getCategoryList(response);
				cctvListUrl = channelCates.get(0).getListUrl();
				guardListUrl = channelCates.get(1).getListUrl();
				localListUrl = channelCates.get(2).getListUrl();
				initJsonData(cctvListUrl);
			}else if(url.equals(cctvListUrl)){
				cctvChannelInfos = ParseUtil.parseDataToCollection(response.optJSONObject("data"), "items", ChannelInfo.class);
				setAdapter(cctvChannelInfos);
			}else if(url.equals(guardListUrl)){
				guardChannelInfos = ParseUtil.parseDataToCollection(response.optJSONObject("data"), "items", ChannelInfo.class);
				setAdapter(guardChannelInfos);
			}else if(url.equals(localListUrl)){
				localChannelInfos = ParseUtil.parseDataToCollection(response.optJSONObject("data"), "items", ChannelInfo.class);
				setAdapter(localChannelInfos);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			initDataFailed(url,102,getString(R.string.server_data_exception));
		}
	}
	 
	private void setAdapter(List<ChannelInfo> infos){
		if(channelInfoAdapter == null){
			channelInfoAdapter = new ChannelInfoAdapter(ChannelListActivity.this, infos, R.layout.channel_list_item_view);
			lvChannelList.setAdapter(channelInfoAdapter);
		}else{
			channelInfoAdapter.setData(infos);
			channelInfoAdapter.notifyDataSetChanged();
		}
//		lvChannelList.endRefresh();
		//sRefreshLayout.setRefreshing(false);
	}
	
	
	
	@Override
	protected void initDataFailed(String url, int errorNo, String strMsg) {
		// TODO Auto-generated method stub
		super.initDataFailed(url, errorNo, strMsg);
		Log.i("zl","errorNo = " + errorNo + ",strMsg = " + strMsg);
		
//		lvChannelList.endRefresh();
	}
	
	private void addMenuOnWindow() {
		try {
			getWindow().addFlags(WindowManager.LayoutParams.class.getField("FLAG_NEEDS_MENU_KEY").getInt(null));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.menu_channel, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
//		//sRefreshLayout.setRefreshing(true);
		currentItem = item.getItemId();
		item.setChecked(true);
		reLoadData(currentItem,false);
		return true;
	}
	
	private void reLoadData(int itemId,boolean isNetWork){
		switch (itemId) {
		case R.id.channel_cctv:
			if(!isNetWork && cctvChannelInfos != null && cctvChannelInfos.size() > 0){
				setAdapter(cctvChannelInfos);
			} else if (cctvListUrl == null) {
				initJsonData(channelNavUrl);
			} else {
				initJsonData(cctvListUrl);
			}
			break;
		case R.id.channel_guard:
			if(!isNetWork && guardChannelInfos != null && guardChannelInfos.size() > 0){
				setAdapter(guardChannelInfos);
			} else if (guardListUrl == null) {
				initJsonData(channelNavUrl);
			} else {
				initJsonData(guardListUrl);
			}
			break;
		case R.id.channel_local:
			if(!isNetWork && localChannelInfos != null && localChannelInfos.size() > 0){
				setAdapter(localChannelInfos);
			} else if (localListUrl == null) {
				initJsonData(channelNavUrl);
			} else {
				initJsonData(localListUrl);
			}
			break;
		default:
			break;
		}
	}
	
	private void onChannelItemClick(int position) {
		ChannelInfo channelInfo = null;
		String categoryUrl = null;
		switch (currentItem) {
		case R.id.channel_cctv:
			categoryUrl = cctvListUrl;
			channelInfo = cctvChannelInfos.get(position);
			break;
		case R.id.channel_guard:
			categoryUrl = guardListUrl;
			channelInfo = guardChannelInfos.get(position);
			break;
		case R.id.channel_local:
			categoryUrl = localListUrl;
			channelInfo = localChannelInfos.get(position);
			break;
		default:
			break;
		}
		
		if(channelInfo == null){
			Toast.makeText(mContext, "数据异常", Toast.LENGTH_SHORT).show();
			return;
		}
		
		VideoInfo vInfo = new VideoInfo();
		vInfo.setTitle(channelInfo.getTitle());
		vInfo.setDetailUrl(channelInfo.getLiveUrl());
		vInfo.setChannelId(channelInfo.getChannelId());
		vInfo.setP2pUrl(channelInfo.getP2pUrl());
		vInfo.setRate(Const.PLAYER_MODE_SD);
//		vInfo.setShareUrl(channelInfo.getShareUrl());
//		vInfo.setRecomUrl(app.getBaseUrls().get(Const.KEY_RECOM_URL).getUrl() + "&p=1&n=100&channel=" + channelInfo.getChannelId());
//		vInfo.setEpgUrl(app.getBaseUrls().get(Const.KEY_EPG_URL).getUrl() +"?&d=0&c=" + channelInfo.getChannelId()); 
//		vInfo.setChannelUrl(cctvListUrl);
		
		vInfo.setFlag(Const.LIVE);
		vInfo.setTimeShift(true);
		vInfo.setOrder(channelInfo.getOrder());
		
		Intent liveIntent = new Intent(ChannelListActivity.this,MediaPlayActivity.class); 
		liveIntent.putExtra(VideoInfo.class.getName(), vInfo);
		liveIntent.putExtra("categoryUrl", categoryUrl);//传频道分类地址
		startActivity(liveIntent);
		overridePendingTransition(R.anim.base_push_right_in,R.anim.base_fade_out);
	}

	@Override
	public void onSlide(View view, int position, int status) {
		// TODO Auto-generated method stub
		if (mLastSlideViewWithStatusOn != null && mLastSlideViewWithStatusOn != view) {
            mLastSlideViewWithStatusOn.shrink();
        }
        if (status == SLIDE_STATUS_ON) {
            mLastSlideViewWithStatusOn = (SlideView) view;
        }else if(status == SLIDE_STATUS_NONE){
        	onChannelItemClick(position);
        }
	}
	

}
